<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /*
        下面两都支持跨页面获取

        sessionStorage：当次访问保存的数据，浏览器或页面关闭才删除
            原始数据类型：直接保存
                如果不是string，自动转换
                setItem(key, value)：key一般是字符串
                getItem(key)：string类型
            引用数据类型
                保存时，需要做特殊处理，因为不支持保存对象。需要通过JSON对象，将对象格式化为JSON格式的字符串
                获取时，取出来是字符串，通过JSON对象，将字符转换为JSON对象或JSON数组
        localStorage：永久保存
        方法都一样

        JSON：是一种文本格式
            对象：{key:value, key:value}，key一定加""
                {key: {key: value, key: value}}
            数组：[
                {key: value},
                {}

            ]
     */
    sessionStorage.setItem("age", 18);
    sessionStorage.setItem("name", "张三");
    console.log(typeof sessionStorage.getItem("age"));
    console.log(typeof sessionStorage.getItem("name"));

    let obj = {
        name: "obj",
        age: 28
    }
    sessionStorage.setItem("obj", obj);//保存是obj的valueOf方法的返回值，一般是[object Object]
    console.log(sessionStorage.getItem("obj"));
    sessionStorage.setItem("obj", JSON.stringify(obj));//保存是obj的valueOf方法的返回值，一般是[object Object]
    console.log(sessionStorage.getItem("obj"));
    console.log(JSON.parse(sessionStorage.getItem("obj")));

    let books = [
        {id: 1, name: 'Java从入门到放弃', price: 80, tdate: '2020-07-01', count: 1, email: "haha"},
        {id: 2, name: 'Vue从入门到放弃', price: 90, tdate: '2020-07-02', count: 1, email: "haha"},
        {id: 3, name: 'Mysql从入门到放弃', price: 100.01, tdate: '2020-07-03', count: 1, email: "haha"},
        {id: 4, name: '啥都从入门到放弃', price: 70.0001, tdate: '2020-07-04', count: 1, email: "hehe"},
        {id: 5, name: 'JavaScript从入门到放弃', price: 60.00, tdate: '2020-07-04', count: 1, email: "hehe"},
        {id: 6, name: 'JavaScript从入门到放弃', price: 50.00, tdate: '2020-07-04', count: 1, email: "hehe"}
    ];

    sessionStorage.setItem("books", books);
    console.log(sessionStorage.getItem("books"));
    sessionStorage.setItem("books", JSON.stringify(books));
    console.log(sessionStorage.getItem("books"));
    console.log(JSON.parse(sessionStorage.getItem("books")) instanceof Array);
    console.log(Array.prototype.isPrototypeOf(JSON.parse(sessionStorage.getItem("books"))));
    JSON.parse(sessionStorage.getItem("books")).forEach(value => console.log(value));

    // 在JS中Map和Set不支持JSON转换
    let map = new Map();
    map.set("name", "haha");
    sessionStorage.setItem("map", map);
    console.log(sessionStorage.getItem("map"));
    sessionStorage.setItem("map", JSON.stringify(map));
    console.log(sessionStorage.getItem("map"));
    //如果用到了map，需要转换为JSON格式的话，需要先将map转换为Object
</script>
</body>
</html>